package com.example.lib_audio.service

import android.app.Service
import android.content.Intent
import android.content.IntentFilter
import android.media.MediaPlayer
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.annotation.RequiresApi
import com.example.lib_audio.audio.AudioController
import com.example.lib_audio.eventbus.AudioLoadEvent
import com.example.lib_audio.eventbus.AudioPauseEvent
import com.example.lib_audio.eventbus.AudioStartEvent
import com.example.lib_audio.tools.AudioHelper
import com.example.lib_base.model.Song
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MusicService:Service() {
    private val audioController = AudioController.getInstance()!!
        private val mNotificationHelper = MyNotification()
    private var mMusicNotificationReceiver = MusicNotificationReceiver()
    private var song:Song? = null


    override fun onCreate() {
        super.onCreate()
        EventBus.getDefault().register(this)
        //动态注册通知
        registerReceiver()
    }

    private fun registerReceiver(){
        val intentFilter = IntentFilter(MyNotification.ACTION_BROADCAST_NOTIFICATION)
        AudioHelper.mContext.registerReceiver(mMusicNotificationReceiver,intentFilter)
    }

    companion object{
        val MUSIC_KEY = "wjb_music"

        //开启一个服务
        fun startService(song: Song){
            val intent = Intent( AudioHelper.mContext,MusicService::class.java)
            intent.putExtra(MUSIC_KEY,song)
            AudioHelper.mContext.startService(intent)
        }
    }


    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

        song = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            intent!!.getSerializableExtra(MUSIC_KEY,Song::class.java)
        } else {
            intent!!.getSerializableExtra(MUSIC_KEY) as Song
        }



        //播放
        song?.let {music->
            audioController.start(music)
        }



        return super.onStartCommand(intent, flags, startId)
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLoadEvent(event: AudioLoadEvent){
        mNotificationHelper.init(event.song)
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onStartEvent(event: AudioStartEvent){
        mNotificationHelper.showStart()
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onPauseEvent(event: AudioPauseEvent){
        mNotificationHelper.showPause()
    }



    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        //销毁通知
        AudioHelper.mContext.unregisterReceiver(mMusicNotificationReceiver)
    }
}